package com.sudu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sudu.dao.TokenUtil;
import com.sudu.domain.User;
import com.sudu.service.UserService;
import com.sudu.tool.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/logins")
@Api
public class UserLoginController {
    @Autowired
    private UserService userService ;

    @Autowired
    private MD5 md5 ;

    @ApiOperation(value = "用户登录")
    @PostMapping
    public Result login(
            @ApiParam(name="request",value="请求体", required = true)
            HttpServletRequest request)  {
        StringBuffer data = new StringBuffer() ;
        String line ;
        BufferedReader reader  ;
        JSONObject jsonObj = null ;

        try {
            reader = request.getReader() ;
            while (null != (line = reader.readLine()) ) {
                data.append(line) ;
                System.out.println("line==========="+line);
                jsonObj = JSON.parseObject(data.toString());
            }
        } catch (Exception e) {
           e.printStackTrace();
        }

        String phone = jsonObj.getString("phone") ;
        String password = jsonObj.getString("password") ;
        User user = userService.fineByPhone(phone) ;
        String salt = user.getSalt() ;
        String md5Password = md5.getMD5Password(password , salt);
        System.out.println(md5Password);
        if (null==user || !user.getPassword().equals(md5Password)) {
            return new Result(Code.LOGIN_ERR , null , "账号或密码不正确 !");
//            throw new LoginException("用户名或密码不正确");
        }
        Map map=new HashMap();
        map.put("username",user.getUsername());
        map.put("id",user.getId());
        String  resObj= JSON.toJSONString(map);
        JSONObject res = JSON.parseObject(resObj);
        //生成一个token返回或者是放进响应头中
        String token = TokenUtil.getToken(user.getId(), user.getPhone());
        return new Result(Code.LOGIN_OK ,res,token);
    }

}
